const state = {
  cartProducts: JSON.parse(window.localStorage.getItem('cart-products')) || []
}
const getters = {
  totalCount(state){
    return state.cartProducts.reduce((count,prod)=>{
      return count + prod.count
    },0)
  },
  totolPrice(state){
    return state.cartProducts.reduce((price, prod)=>{
      return price + prod.totalPrice
    },0).toFixed(2)
  },
  checkedTotalCount(state){
    return state.cartProducts.reduce((sum,prod)=>{
      if(prod.isChecked){
        sum+=prod.count
      }
      return sum
    },0)
  },
  chenckedTotolPrice(state){
    return state.cartProducts.reduce((sum,prod)=>{
      if(prod.isChecked){
        sum += prod.totalPrice
      }
      return sum
    },0)
  }
}
const mutations = {
  addToCart(state,product){
    const prod = state.cartProducts.find((item) => item.id === product.id)
    // console.log(prod);
    if(prod){
      prod.count++,
      prod.isChecked = true
      prod.totalPrice += product.price
    }else{
      state.cartProducts.push({
        ...product,
        count:1,
        totalPrice:product.price,
        isChecked:true
      })
    }
  },
  deleteFromCart(state,prodId){
    const index = state.cartProducts.findIndex(item => item.id === prodId)
    index !== -1 && state.cartProducts.splice(index,  1)
  },
  updateAllProductsChecked(state, checked){
    state.cartProducts.forEach(prod => {
      prod.isChecked = checked
    })
  },
  updateProductChecked(state,{prodId,checked}){
    const prod = state.cartProducts.find(prod => prod.id === prodId)
    prod && (prod.isChecked = checked)
  },
  updateProductCount(state,{
    prodId, count
  }){
    const prod = state.cartProducts.find(item => item.id === prodId)
    if(prod) {
      // console.log(prod);
      prod.count = count 
      prod.totalPrice = count * prod.price
    }
  }
}
const actions = {}
export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}